#!/usr/bin/env python
import os
import glob



class PluginHandler:
    def __init__(self, root):
        self.root = root
        
        self.plugins = self.getPlugins()
    
    def getPlugins(self):
        """The procedure which finds and loads plugins"""
        #Scans the plugins folder for subfolders
        folder = os.path.abspath(self.root.config.pluginFolder)
        
        #Seek plugins, make plugin objects
        avaiblePlugins = []
        namesAndVers = []
        for path in glob.glob(os.path.join(folder, "*")):
            if os.path.isdir(path):
                pluginName = os.path.split(path)[1]
                plugin = self.getPlugin(pluginName)
                
                if plugin:
                    avaiblePlugins.append(plugin)
                    namesAndVers.append((plugin.name, plugin.version))
        
        #Check dependencies
        validPlugins = []
        for plugin in avaiblePlugins:
            if len(plugin.dependencies) == 0:
                validPlugins.append(plugin)
            
            satisfiedDependencies = []
            for dependency in plugin.dependencies:
                for dependency2 in namesAndVers:
                    if dependency[0] == dependency2[0]:
                        if dependency2[1] >= dependency[1]:
                            satisfiedDependencies.append(dependency)
            
            valid = True
            for dependency in plugin.dependencies:
                if not dependency in satisfiedDependencies:
                    valid = False
                    break
            
            if valid:
                validPlugins.append(plugin)
        
        #Load plugins
        loadedPlugins = []
        for plugin in validPlugins:
            if plugin.load(self.root):
                loadedPlugins.append(plugin)
        
        return loadedPlugins
    
    def getPlugin(self, pluginName):
        """Takes the plugin name, returns a Plugin object"""
        try:
            module = __import__("plugins." + pluginName + "." + pluginName)
            return module.Plugin()
        except ImportError:
            return None
        except AttributeError:
            return None

class Plugin:
    def __init__(self):
        self.name = "Default"
        self.comment = "Default"
        self.author = "Francesco Mastellone"
        self.license = "GPL"
        self.copyright = "Francesco Mastellone, 2008"
        
        self.order = 0 #Loading order
        self.dependencies = []
    
    def update(self):
        pass
    
    def draw(self, surface):
        pass
    
    def load(self, application):
        """Loads plugin into the application"""
        application.updateInstances.append(plugin)
        application.drawInstances.append(plugin)
        return True